﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PerformanceExamine.Common
{
    public class FormFactory
    {
        //private static FormUserManager formUserManager;
        //private static FormBaseManager formBaseManager;
        private static Form form;
        private static List<Form> forms = new List<Form>();

        //public static Form CreateForm(int index)
        //{ 
        //    HideFormAll();
        //    switch (index)
        //    {
        //        case 0:
        //            if (formUserManager==null)
        //            {
        //                formUserManager = new FormUserManager();
        //                forms.Add(formUserManager);
        //            }
        //            form=formUserManager; 
        //            break;
        //        case 1:
        //            if (formBaseManager==null)
        //            {
        //                formBaseManager = new FormBaseManager();  
        //                forms.Add(formBaseManager);
        //            }
        //            form = formBaseManager;
        //            break;
        //        default:
        //            break;
        //    }
        //    return form;
        //}

        //使用静态构造器进行讲反射进行缓存
        private static List<Type> types = new List<Type>();
        static FormFactory()
        {
            Assembly ass = Assembly.Load("PerformanceExamine");
            types = ass.GetTypes().ToList();
        }

        public static Form CreateForm(string formName)
        {
            //每次执行都要加载一反射整个程序集，性能消耗太大
            //Assembly ass = Assembly.Load("PerformanceExamine");
            //List<Type> types = ass.GetTypes().ToList();
            HideFormAll();       
            Form form = forms.Find(m => m.Name == formName);
            if (form==null)
            {
                Type type = types.Find(m => m.Name == formName);
                form = (Form)Activator.CreateInstance(type);
                forms.Add(form);
            }
            return form;
        }
        public static void HideFormAll()
        {
            foreach (Form form in forms)
            {
                form.Hide();
            }
        }
    }
}
